package com.yonyou.pmclouds.basecom.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.entity.AdditionalPropertiesVOWrapper;
import com.yonyou.pmclouds.basecom.entity.Entity;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.rmiitf.ListCommonPropertiesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
public class CommonPropertiesProcessor {
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ListCommonPropertiesService propertiesService;

    public <T extends Entity> AdditionalPropertiesVOWrapper[] wrapAdditionalProps(T[] vos) throws BusinessException {
        //判断其插入数组是否为空
        if (ArrayUtils.isEmpty(vos)) {
            return new AdditionalPropertiesVOWrapper[0];
        }
        AdditionalPropertiesVOWrapper[] wrappers = new AdditionalPropertiesVOWrapper[vos.length];
        //  创建一个单据ID的数组
        String[] ids = new String[vos.length];
        for (int i = 0; i < ids.length; i++) {
            ids[i] = (String) vos[i].pkFiledValue();
        }
        //得到的数据为外层map的key为单据ID，内层Map中的key为COMMENT_COUNT即评论属性名称,value为评论数
        Map<String, Map<String, Object>> additionProperties = propertiesService.fetchAdditionProperties(ids);
        for (int i = 0; i < vos.length; i++) {
            wrappers[i] = new AdditionalPropertiesVOWrapper<>(vos[i]);
            Map<String, Object> properties = additionProperties.get(vos[i].pkFiledValue());
            if (properties == null || properties.isEmpty()) {
                continue;
            }
            for (Map.Entry<String, Object> entry : properties.entrySet()) {
                wrappers[i].addProperties(entry.getKey(), entry.getValue());
            }
        }
        return wrappers;
    }
}
